/*
 * Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
 * Note:
 * - Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
 * - The solution set must not contain duplicate triplets.
 *
 * For example, given array S = {-1 0 1 2 -1 -4},
 * A solution set is:
 *   (-1, 0, 1)
 *   (-1, -1, 2)
 */
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        vector<vector<int> > res;
        int size = num.size();
        if (size < 3) {
            return res;
        }
        std::sort(num.begin(), num.end());
        for (int i = 0; i < size-2; i++) {
            if (i > 0 && num[i] == num[i-1]) { /* remove dups */
                continue;
            }
            int j = i + 1;
            int k = size - 1;
            while (j < k) {
                int sum = num[j] + num[k];
                if (k < size-1 && num[k] == num[k+1]) { /* remove dups */
                    k--;
                } else if (sum + num[i] > 0) {
                    k--;
                } else if (sum + num[i] < 0) {
                    j++;
                } else {
                    vector<int> t;
                    t.push_back(num[i]);
                    t.push_back(num[j]);
                    t.push_back(num[k]);
                    res.push_back(t);
                    j++;
                    k--;
                }
            }
        }
        return res;
    }
};

int main() {
    return 0;
}
